import {Component,  OnInit, HostListener} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {MainMenuService} from '../main-menu.service';
import {StorageService} from '../../services/storage.service';
import {EventBusService} from '../../services/event-bus.service';
import {ConfirmationService} from 'primeng/primeng';

@Component({
    selector: 'app-main-menu',
    templateUrl: './main-menu.component.html',
    styleUrls: ['./main-menu.component.scss']
})
export class MainMenuComponent  implements OnInit {
    userName: string ='Coder浪漫的野马';
    showmenu = true;
    showMessage: boolean = false;
    menus = [];
    menuActive: boolean;
    public isCollapse: boolean = false;
    flag;
    menusIconsAndRoutes =
        [
            { id: '1',
                icon: 'fa-superpowers',
                name: '设备管理',
                children:  [
                    {icon: ' ', route: 'equipment' , name: '设备总览'},
                    {icon: ' ', route: 'equipment/import' , name: '导入设备'},
                    {icon: ' ', route: 'equipment/search' , name: '设备检索'},
                    {icon: '', route: 'equipment/info' , name: '设备检测'}
                ]
            },
            { id: '2',
                icon: 'fa-assistive-listening-systems',
                name: '巡检管理',
                children:  [
                    { icon: '', route: 'inspection/view', name: '巡检总览' },
                    { icon: '', route: 'inspection/plan', name: '巡检计划' },
                    { icon: '', route: 'inspection/talk', name: '巡检报告' },
                    { icon: '', route: 'inspection/inspectionSetting/object', name: '巡检配置' }
                ]
            },
            { id: '3',
                icon: 'fa-line-chart',
                name:'报障管理',
                children:  [

                    { icon: '', route: 'report/review', name: '报障发起'},
                    { icon: '', route: 'report/history', name: '历史报障'},
                    { icon: '', route: 'report', name: '今日总览'},
                ]
            },
            { id: '4',
                icon: 'fa-calendar-check-o',
                name: '值班管理',
                children:  [
                    { icon: '', route: 'duty/overview' , name: '值班总览' },
                    { icon: '', route: 'duty/current'  , name: '当前值班'},
                    { icon: '', route: 'duty/manage' , name: '值班管理' },
                    { icon: '', route: 'duty/dutyshift'  , name: '调班总览'},
                    { icon: '', route: 'duty/setting' , name: '班次设置' },
                    { icon: '', route: 'duty/handoveroverview' , name: '交接班总览' },
                    { icon: '', route: 'duty/minhandoveroverview' , name: '我的交接班' },
                ]
            },
            { id: '5',
                icon: 'fa-university',
                name: '库房管理',
                children:  [
                    { icon: '', route: 'inventory/inventory' , name: '库存总览'},
                    { icon: '', route: 'inventory/flow/overview' , name: '入库管理'},
                    { icon: '', route: 'inventory/borrowManage/outbound' , name: '借用管理'},
                    { icon: '', route: 'inventory/requisitionmanage/requestionOverview' , name: '领用管理'},
                    { icon: '', route: 'inventory/material' , name: '物品维护'}
                ]
            },
            { id: '6',
                icon: 'fa-cogs',
                route:'capacity/capacityBasalDatas/capviewroot',
                name: '空间管理',
                children:  [
                    // { icon: '', route: 'capacity/capacityBasalDatas/capviewroot' }
                ]
            },
            { id: '7',
                icon: 'fa-cogs',
                name: '知识库',
                route: 'knowledge/basaldata',
                children:  [
                    { icon: '', route: 'knowledge/chart' , name: '知识管理'},
                    { icon: '', route: 'knowledge/klgmine' , name: '我的知识库'}
                ]
            },
            { id: '8',
                icon: 'fa-wrench',
                name: '运维管理',
                route: '',
                children:  [
                    { icon: '', route: 'maintenance/malfunctionBase/malfunctionOverview' , name: '故障管理'},
                    { icon: '', route: 'reqForService/rfsBase/serviceOverview' , name: '服务请求'}
                ]
            },
            { id: '13',
                icon: 'fa-bars',
                name: '系统配置',
                children:  [
                    { icon: '', route: 'system/person' , name: '人员管理'},
                    { icon: '', route: 'system/jur' , name: '权限管理'}
                ]
            },
            { id: '14',
                icon: 'fa-life-saver',
                name:'报表报告',
                children:  [
                    { icon: '', route: 'reports/make' , name: '制作报表'},
                    { icon: '', route: 'reports/view' , name: '查看报表'},
                    { icon: '', route: 'reports/send', name: '发送配置' },
                ]
            }
        ];
    constructor(
        private mainMenuService: MainMenuService ,
        private storageService: StorageService,
        private router: Router,
        private confirmationService: ConfirmationService,
        private eventBusService: EventBusService,
        private activatedRoute: ActivatedRoute
    ) {}
    ngOnInit() {
        if (window.sessionStorage.getItem('route')){
            this.showmenu = false;
            return;
        }
        this.userName = this.storageService.getUserName('userName');
        // this.mainMenuService.getMainMenu().subscribe(data => {
        //     for (let i = 0; i < data.length; i ++) {
        //         let item = data[i];
        //         let childrens = item.children;
        //         item['id'] = i + 1;
        //         item['isOpen'] = false;
        //         (childrens) && (item['hasChildrens'] = true);
        //         (!childrens) && (item['hasChildrens'] = false);
        //         if (childrens) {
        //             for (let j = 0; j < childrens.length; j ++) {
        //               let temp = childrens[j];
        //               temp['active'] = false;
        //             }
        //         }
        //     }
        //     this.menus = data;
        //     console.log(this.menus);

        //     if (this.storageService.getCurrentMenuItem('xy')) {
        //         let {x, y} = JSON.parse(this.storageService.getCurrentMenuItem('xy'));
        //         for (let i = 0; i < this.menus.length; i++) {
        //             for (let j = 0; j < this.menus[i].children.length; j++) {
        //                 this.menus[i].children[j]['active'] = false;
        //             }
        //         }
        //       let redirectUrl = this.menus[x]['children'][y]['route'];
        //       this.router.navigate(['index/'+redirectUrl]);
        //       this.menus[x]['children'][y]['active'] = true;
        //     }else{
        //       let redirectUrl = this.menus[0]['children'][0]['route'];
        //       this.router.navigate(['index/'+redirectUrl]);
        //       this.menus[0].children[0]['active'] = true;
        //     }
        // }, (err: Error) => {
        //     let message ;
        //     if (JSON.parse(JSON.stringify(err)).status === 504 || JSON.parse(JSON.stringify(err)).status === 0){
        //         message = '似乎网络出现了问题，请联系管理员或稍后重试';
        //       this.confirmationService.confirm({
        //         message: message,
        //         rejectVisible: false,
        //       });
        //       return
        //     }else if (err['message'].search(/Invalid/) !== -1){
        //         this.logOut();
        //         return;
        //     }
        //   this.confirmationService.confirm({
        //     message: err['message'],
        //     rejectVisible: false,
        //   });
        // });
        this.menus = this.menusIconsAndRoutes;
        this.eventBusService.topToggleBtn.subscribe(value => {
            this.toggleMenuAll(value);
        });
        this.eventBusService.menuActice.subscribe(value => {
            this.menuActive = value;
        });
    }
    private toggleMenuAll(isCollapse: boolean): void {
        this.isCollapse = isCollapse;
        this.menus.forEach(item => {
            item.isOpen = false;
        });
    }
    logOut(){
        window.sessionStorage.clear();
        this.router.navigateByUrl('/login');
    }
    closeMenu(x, y){
        this.storageService.setCurrentMenuItem('xy', {x: x, y: y});
        for (let i = 0; i < this.menus.length; i++){
            for (let j = 0 ; j < this.menus[i].children.length; j++){
                this.menus[i].children[j]['active'] = false;
            }
        }
        this.menus[x].children[y]['active'] = true;
        this.eventBusService.menuActice.next(false);
        this.flag = false;
    }
    public toggleMenuItem(event, menu): void {
        if (menu['route']) {
            this.router.navigateByUrl('/index/' + menu['route']);
        }

        menu.isOpen = !menu.isOpen;
        // 折叠状态下只能打开一个二级菜单层
        if (this.isCollapse) {
            let tempId = menu.id;
            this.menus.forEach(item => {
                if (item.id !== tempId) {
                    item.isOpen = false;
                }
            });
        }
        let tempId = menu.id;
        this.menus.forEach(item => {
            if (item.id !== tempId) {
                item.isOpen = false;
            }
        });
        if (this.menuActive){
            this.flag = true;
        }
    }
    @HostListener('body:click', ['$event'])
    public onBodyClick(event): void {
        if (this.isCollapse && event.clientX > 75) {
            if (this.flag) {return};
            this.menus.forEach(item => {
                item.isOpen = false;
            });
        }
    }
}
